go to previous page   go to home page   go to next page

What is going on with:

outCel.setText( celsTemp+"" );

Answer:

The text that appear in the text field outCel is set with its setText method. That parameter for that method should be reference to a String. But celsTemp is an integer, and will not work. However in the following,

celsTemp+"" 

+   means "string concatenation" so the integer in celsTemp is converted to a String, an empty string is concatenated onto it, which results in a String, which is the proper type for the parameter.


Complete Application

The complete application is below. Of course, you will want to copy this to a file, compile and run it.

import java.awt.*; 
import java.awt.event.*;
import javax.swing.* ;
    
public class FahrConvert extends JFrame implements ActionListener
{
  JLabel heading  = new JLabel("Convert Fahrenheit to Celsius");
  JLabel inLabel  = new JLabel("Fahrenheit    ");
  JLabel outLabel = new JLabel("Celsius ");
   
  JTextField inFahr = new JTextField( 7 );
  JTextField outCel = new JTextField( 7 );
    
  int fahrTemp ;
  int celsTemp ;
    
  FahrConvert( String title )   
  {  
     super( title );
     setLayout( new FlowLayout() );   
    
     inFahr.addActionListener( this );
     outCel.setEditable( false );

     add( heading );
     add( inLabel );  
     add( outLabel ); 
     add( inFahr );   
     add( outCel );   
     
     setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }
    
  // The application
  public int convert( int F )  
  {
    return ( (F-32) * 5 ) / 9;
  }
   
  public void actionPerformed( ActionEvent evt)  
  {
    String userIn = inFahr.getText() ;
    fahrTemp = Integer.parseInt( userIn ) ;
   
    celsTemp = convert( fahrTemp ) ;
   
    outCel.setText( celsTemp+"" );
    repaint();   
  }
     
  public static void main ( String[] args )
  {
    FahrConvert   fahr  = new FahrConvert( "F to C" ) ;
    
    fahr.setSize( 200, 150 );     
    fahr.setVisible( true );      
  }
   
}

QUESTION 7:

What happens if the user enters text that Integer.parseInt() cannot convert into an integer?